# chat/consumers.py
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json

from django.core import cache
from django.utils.http import urlencode, urlunquote

from chat.models import UserChat


class ChatConsumer(WebsocketConsumer):

    def connect(self):
        # 在地址上传token过来， 用token查询用户id
        # 将uid，加入redis

        # 将ucg加入redis
        uid = 1
        print(self.channel_name)

        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        # print(self.scope)

        ucgs = UserChat.objects.get(id=uid).belong_groups.all()
        for ucg in ucgs:
            async_to_sync(self.channel_layer.group_add)(
                ucg.group_name,
                self.channel_name
            )

        self.accept()



        # print(self.scope['query_string'].decode('utf-8', 'ignore'))

        # print(type(self.channel_name))
        # print(dir(self.channel_layer))
        # cache.cache.set('123', self, 80)
        # print(cache.)

        # self.channel_layer.send(text_data=json.dumps({
        #     'message': '12312312',
        # }))

        self.send(text_data=json.dumps({
            'message': 12312312,
        }))

    def disconnect(self, close_code):
        # 从redis里通过channel_name获取uid
        uid = 1

        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

        ucgs = UserChat.objects.get(id=uid).belong_groups.all()
        for ucg in ucgs.values_list('group_name'):
            async_to_sync(self.channel_layer.group_discard)(
                ucg.group_name,
                self.channel_name
            )

    # Receive message from WebSocket
    def receive(self, text_data):
        uid = 1

        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

        ucgs = UserChat.objects.get(id=uid).belong_groups.all()
        for ucg in ucgs:
            async_to_sync(self.channel_layer.group_send)(
                ucg.group_name,
                {
                    'type': 'chat_message',
                    'message': message
                }
            )


    # Receive message from room group
    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))
